﻿using AutoMapper;
using MediatR;
using S.Produce.Api.Application.Commands.HistoryCommands;
using S.Produce.Domains;
using S.Produce.Infrastructure;

namespace S.Produce.Api.Application.CommandHandlers.HistoryCommandHandlers
{
    public class HistoryCreateCommandHandler : IRequestHandler<HistoryCreateCommand, int>
    {
        private readonly IRepository<History> repository;
        private readonly IMapper mapper;

        /// <summary>
        /// 构造方式注入
        /// </summary>
        /// <param name="repository"></param>
        public HistoryCreateCommandHandler(IRepository<History> repository, IMapper mapper)
        {
            this.repository = repository;
            this.mapper = mapper;
        }

        /// <summary>
        /// 添加种母历史记录信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> Handle(HistoryCreateCommand request, CancellationToken cancellationToken)
        {
            var info = await repository.SelAllAsync(x => x.Earbugles == request.Earbugles);
            var first = info.Where(x => !x.IsDel && !x.IsEnd);
            foreach (var item in first)
            {
                if (item.Earbugles == request.Earbugles && item.AtPresentParity == request.AtPresentParity)
                {
                    //耳号相同，当前胎次相同，说明是修改本条数据
                    request.UpdateBy = request.CreateBy;
                    request.UpdateDate = DateTime.Now;
                    request.RecordId = item.RecordId;
                    return await repository.UpdateAsync(mapper.Map<HistoryCreateCommand, History>(request, item));
                }
                else
                {
                    continue;
                }
            }
            request.CreateDate = DateTime.Now;
            request.UpdateBy = null;
            request.UpdateDate = null;
            //没有匹配到需要修改的历史记录，则添加一条新的历史记录
            var history = new History();
            return await repository.CreateAsync(mapper.Map<HistoryCreateCommand, History>(request, history));
        }
    }
}
